package org.gdkm.springbootxiangmushizhan.controller.admin;

import com.github.pagehelper.PageInfo;
import org.gdkm.springbootxiangmushizhan.domain.vo.UserAdminVO;
import org.gdkm.springbootxiangmushizhan.service.IUserService;
import org.gdkm.springbootxiangmushizhan.domain.po.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@Controller
@RequestMapping("/admin/user")
public class UserAdminController {
    @Autowired
    private IUserService userService;

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    // 跳转到用户管理页面，分页查询
    @GetMapping("")
    public String list(@RequestParam(value = "page", defaultValue = "1") int page,
                      @RequestParam(value = "count", defaultValue = "10") int count,
                      HttpServletRequest request) {
        PageInfo<UserAdminVO> pageInfo = userService.getAllUsersWithPage(page, count);
        request.setAttribute("users", pageInfo);
        return "back/user_list";
    }

    // 删除用户
    @PostMapping("/delete")
    @ResponseBody
    public String delete(@RequestParam Integer id) {
        userService.deleteUserById(id);
        return "ok";
    }

    // 禁止/允许用户
    @PostMapping("/valid")
    @ResponseBody
    public String updateValid(@RequestParam Integer id, @RequestParam Integer valid) {
        userService.updateUserValidById(id, valid);
        return "ok";
    }

    // 获取单个用户信息（编辑弹窗回显）
    @GetMapping("/info")
    @ResponseBody
    public User getUserInfo(@RequestParam Integer id) {
        return userService.selectUserById(id);
    }

    // 保存用户信息（编辑保存）
    @PostMapping("/save")
    @ResponseBody
    public String saveUser(@ModelAttribute User user) {
        user.setModified(new java.util.Date());
        // 查询原有用户
        User oldUser = userService.selectUserById(user.getId());
        // 如果新密码和原密码不一样，说明用户修改了密码，需要加密
        if (user.getPassword() != null && !user.getPassword().equals("") && !user.getPassword().equals(oldUser.getPassword())) {
            user.setPassword(passwordEncoder.encode(user.getPassword()));
        } else {
            // 没有修改密码，保持原有密码
            user.setPassword(oldUser.getPassword());
        }
        userService.updateUserById(user);
        return "ok";
    }

    // 新增用户
    @PostMapping("/add")
    @ResponseBody
    public String addUser(@ModelAttribute User user) {
        java.util.Date now = new java.util.Date();
        user.setCreated(now);
        user.setModified(now);
        user.setValid(1);
        // 密码加密
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        userService.insertUser(user);
        // 只分配普通用户权限（authority_id=1）
        if (user.getId() != null) {
            userService.insertUserAuthority(user.getId(), 2); // 2为普通用户
        }
        return "ok";
    }
} 